package com.itany.shop.dao.impl;

import com.itany.shop.dao.UserDao;
import com.itany.shop.entity.User;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.rowmapper.UserRowMapper;
import com.itany.shop.util.JDBCTemplate;

import java.util.List;

/**
 * @author MissChen
 * @date 2024年03月29日 9:52
 */
public class UserDaoImpl implements UserDao {
    JDBCTemplate jdbcTemplate = (JDBCTemplate) ObjectFactory.getObject("jdbc");

    @Override
    public void insertUser(User user) {
        String sql = new StringBuffer()
                .append(" insert into ")
                .append(" t_user ")
                .append(" (username,password,phone,address) ")
                .append(" values  ")
                .append(" (?,?,?,?) ")
                .toString();
        jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getPhone(), user.getAddress());
    }

    @Override
    public User selectByUsername(String username) {
        String sql = new StringBuffer()
                .append(" select id,username,password,phone,address ")
                .append(" from ")
                .append(" t_user ")
                .append(" where   ")
                .append("  username=? ")
                .toString();
        List<User> users = jdbcTemplate.query(sql, new UserRowMapper(), username);
        return users.isEmpty() ? null : users.get(0);
    }

    @Override
    public User selectByUsernameAndPassword(String username, String password) {
        String sql = new StringBuffer()
                .append(" select id,username,password,phone,address ")
                .append(" from ")
                .append(" t_user ")
                .append(" where   ")
                .append("  username=? and password=?  ")
                .toString();
        List<User> users = jdbcTemplate.query(sql, new UserRowMapper(), username, password);
        return users.isEmpty() ? null : users.get(0);
    }
}
